package com.open4cn.simulator.protocol.huagao;

import com.open4cn.simulator.core.device.DeviceStatus;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @author yinxiaopeng
 * @version 1.0.0
 * @company 致景科技
 * @department 飞梭BU/研发
 * @description 华高心跳
 * @Email yinxiaopeng@zj.tech
 * @date 2022-05-06 13:40
 */
@ChannelHandler.Sharable
public class HuaGaoHeartbeatHandler extends ChannelInboundHandlerAdapter {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Timer timer = new Timer();

    private DeviceStatus deviceStatus;

    // 设备站号
    private String stationNo;

    public HuaGaoHeartbeatHandler(DeviceStatus deviceStatus, String stationNo) {
        this.deviceStatus = deviceStatus;
        this.stationNo = stationNo;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (deviceStatus.isRunning()) {
                    ByteBuf byteBuf = Unpooled.buffer();
                    byteBuf.writeBytes(heartbeatMsg().toString().getBytes());
                    ctx.channel().writeAndFlush(byteBuf);
                }
            }
        }, 100L, 3000L);
        super.channelActive(ctx);
    }


    private Object heartbeatMsg() {
        return "站号" + stationNo + "心跳";
    }
}
